package jmine.tec.persist.schema.impl.dialects;

import java.sql.Types;
import java.util.Collection;
import java.util.List;

import jmine.tec.persist.schema.api.SchemaColumn;
import jmine.tec.persist.schema.api.SchemaElement;
import jmine.tec.persist.schema.impl.elements.SequenceElement;

import org.hibernate.dialect.MySQL5InnoDBDialect;

/**
 * Dialect para base de dados MySQL
 * 
 * @author lundberg
 */
public class MySQLDialect extends AbstractSqlDialect {

    private static final int MAX_TINY = 3;

    private static final int MAX_SMALL = 5;

    private static final int MAX_INTEGER = 10;

    private static final int MAX_BIGINT = 21;

    /**
     * Construtor
     */
    public MySQLDialect() {
        super(new MySQL5InnoDBDialect());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String renderType(int code, int length, int precision, int scale) {
        if (Types.NUMERIC == code && scale == 0) {
            if (precision < MAX_TINY) {
                return super.renderType(Types.TINYINT, length, precision, scale);
            } else if (precision < MAX_SMALL) {
                return super.renderType(Types.SMALLINT, length, precision, scale);
            } else if (precision < MAX_INTEGER) {
                return super.renderType(Types.INTEGER, length, precision, scale);
            } else if (precision < MAX_BIGINT) {
                return super.renderType(Types.BIGINT, length, precision, scale);
            } else {
                return super.renderType(code, length, precision, scale);
            }
        } else {
            return super.renderType(code, length, precision, scale);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<String> renderIdentityPrimaryKey(String table, String name, SchemaColumn column) {
        String type = this.renderType(column.getCode(), column.getLength(), column.getPrecision(), column.getScale());
        return this.format("ALTER TABLE %s MODIFY %s %s NOT NULL AUTO_INCREMENT UNIQUE", table, column.getName(), type);
    }

    /**
     * {@inheritDoc}
     * 
     * @see jmine.tec.persist.schema.impl.dialects.AbstractSqlDialect#postProcessSchema(java.util.List, java.util.Collection)
     */
    @Override
    public List<String> postProcessSchema(List<String> schemaStatements, Collection<? extends SchemaElement> elements) {
        for (SchemaElement schemaElement : elements) {
            if (schemaElement instanceof SequenceElement) {
                SequenceElement seq = (SequenceElement) schemaElement;
                if (seq.getTableName() != null && seq.getInitialValue() != null && seq.getInitialValue() > 1) {
                    schemaStatements.add("alter table " + seq.getTableName() + " auto_increment = " + seq.getInitialValue());
                }
            }
        }
        return schemaStatements;
    }

}
